﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;

namespace Jiubang.Wap {
    /// <summary>
    /// 查询字符串参数管理类，LinkHelper类使用该类型管理查询参数
    /// </summary>
    internal sealed class QueryParams : IEnumerable<KeyValuePair<string, string>> {
        private NameValueCollection collection;
        private bool @readonly;

        /// <summary>
        /// 当前调用处于页面请求中时根据QueryString集合初始化。
        /// 否则采用默认的NameValueCollection执行初始化。
        /// </summary>
        public QueryParams() {
            var context = HttpContext.Current;
            if (context == null) {
                collection = new NameValueCollection();
                @readonly = false;
            } else {
                collection = context.Request.QueryString;
                @readonly = true;
            }
        }

        /// <summary>
        /// 获取或设置查询参数。
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string this[string name] {
            get { return collection[name]; }
            set {
                if (string.IsNullOrEmpty(name))
                    throw new ArgumentNullException("name");
                var items = collection;
                if (@readonly) {
                    items = new NameValueCollection(collection);
                    collection = items;
                    @readonly = false;
                }
                items.Set(name, value);
            }
        }

        #region IEnumerable<KeyValuePair<string,string>> Members

        /// <summary>
        /// 获取以键值对方式返回的枚举器
        /// </summary>
        /// <returns></returns>
        public IEnumerator<KeyValuePair<string, string>> GetEnumerator() {
            var items = collection;
            for (var i = 0; i < items.Count; i++) {
                yield return new KeyValuePair<string, string>(items.GetKey(i), items.Get(i));
            }
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        #endregion
    }
}